package com.system.manager.modules.authorized.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.authorized.entity.RoleMenu;
import com.system.manager.modules.authorized.mapper.RoleMenuMapper;
import com.system.manager.modules.authorized.service.IRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.manager.modules.authorized.service.SysMenuService;
import com.system.manager.modules.authorized.vo.RoleMenuVo;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yxp
 * @since 2021-10-18
 */
@Transactional
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    /**
     * 更新当前角色的权限
     *
     * @param roleMenuVo
     * @return
     */
    @Override
    public boolean updateRoleMenusId(RoleMenuVo roleMenuVo) {
        try {
            // 1.移除先前的这个角色的权限
            UpdateWrapper<RoleMenu> wrapper = new UpdateWrapper<>();
            wrapper.eq("role_id", roleMenuVo.getRoleId());
            remove(wrapper);

            // 2.插入新增的权限
            RoleMenu roleMenu = new RoleMenu();
            roleMenuVo.getMenusId().forEach((menuId) -> {
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(roleMenuVo.getRoleId());

                save(roleMenu);
            });

        } catch (Exception e) {
            e.printStackTrace();
            // 3.出现异常，抛出
            throw new SysException();
        }

        return true;
    }

}
